<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\UserCode;
use app\common\tool\Result;
use app\common\model\User;
use think\exception\ValidateException;
use think\Response;

class Retrieve extends Base
{
    public function index(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Retrieve');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }
        //校验短信验证码
        $res = UserCode::verifyMsgCode($param['mobile'], $param['captcha'], 'retrievePassword');
        if ($res !== true) return Result::fail($res);
        try {
            $user = User::where(['mobile' => $param['mobile']])->find();
            if (!$user) {
                throw new \Exception('该手机号不存在');
            }
            $type = $param['type'];
            if ($user->$type == md5($param['password'])) {
                throw new \Exception('新密码与原密码一致，请更换');
            }
            $user->$type = md5($param['password']);
            if ($type == 'password') {
                $user->token = md5(json_encode($user) . time());
                $msg = '您的登录密码已找回，请牢记您的新密码';
            } else {
                $msg = '您的支付密码已找回，请牢记您的新密码';
            }
            $user->save();

        } catch (\Exception $e) {

            return Result::fail($e->getMessage());
        }

        return Result::success($msg);
    }
}